//
//  MDDGoodsDetailViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/3/17.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "MDDGoodsDetailViewController.h"
#import "GoodInfoCell.h"
#import "StoreInfoCell.h"
#import "RemGoodsCell.h"
#import "StoreDetailViewController.h"
#import "StoreDetailViewController.h"
#import "AddCartOrBuyView.h"
#import "LZCartViewController.h"
#import "ImageItemCell.h"
#import "UIView+LLXAlertPop.h"

@interface MDDGoodsDetailViewController ()<AxcBannerViewDataSource,AxcBannerViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *selfTableView;
@property (nonatomic, strong) AxcUI_BannerView *bannerView;
@property (nonatomic,strong) NSMutableArray *bannerList;
@property (weak, nonatomic) IBOutlet UIButton *cartBtn;
@property (weak, nonatomic) IBOutlet UIButton *phoneBtn;
@property (nonatomic,strong) AddCartOrBuyView * popView;
@property (nonatomic, strong) NSMutableDictionary *imageHeightArray;
@end

@implementation MDDGoodsDetailViewController

-(void)rightAction:(UIButton *)sender
{
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, self.goodId, @"goodsid");
    setDickeyobj(parameters, @"1", @"add");
    if ([self.goodItem.isCollection isEqualToString:@"0"]) {
        setDickeyobj(parameters, @"true", @"isStar");
    }else{
        setDickeyobj(parameters, @"false", @"isStar");
    }
    [PPNetworkHelper POST:app_person_collectionGoods parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            if ([self.goodItem.isCollection isEqualToString:@"0"]) {
                self.goodItem.isCollection = @"1";
            }else{
                self.goodItem.isCollection = @"0";
            }
            if ([self.goodItem.isCollection isEqualToString:@"0"]) {
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心"] action:@selector(rightAction:)];

            }else{
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心2") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心2"] action:@selector(rightAction:)];
            }
        }else{
            
        }
        
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
- (IBAction)goCartAction:(id)sender {//进入购物车界面
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    LZCartViewController * cart = [[LZCartViewController alloc]init];
    cart.formDetail = YES;
    [self.navigationController pushViewController:cart animated:YES];
}
- (IBAction)buyAction:(id)sender {
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    [self.popView  removeFromSuperview];
    self.popView = [[[NSBundle mainBundle] loadNibNamed:@"AddCartOrBuyView" owner:self options:nil] firstObject];
    self.popView.axcUI_Size = CGSizeMake(mScreenWidth, mScreenHeight*2/3);
    
    self.popView.goodItem = self.goodItem;
    self.popView.pushRoot = self;
    [GKCover translucentCoverFrom:mKeyWindow content:self.popView animated:YES];
}
- (IBAction)addCartAction:(id)sender {
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    [self.popView  removeFromSuperview];
    self.popView = [[[NSBundle mainBundle] loadNibNamed:@"AddCartOrBuyView" owner:self options:nil] firstObject];
    self.popView.axcUI_Size = CGSizeMake(mScreenWidth, mScreenHeight*2/3);
    
    self.popView.goodItem = self.goodItem;
    self.popView.pushRoot = self;
    [GKCover translucentCoverFrom:mKeyWindow content:self.popView animated:YES];
}
- (IBAction)phoneAction:(id)sender {
    NSArray *arrayTitle = [self.goodItem.telphone componentsSeparatedByString:@","];
    UIColor *color = [UIColor AxcUI_colorWithHexCode:@"#676767"];
    [self.view createAlertViewTitleArray:arrayTitle textColor:color font:[UIFont systemFontOfSize:16] actionBlock:^(UIButton * _Nullable button, NSInteger didRow) {
        //获取点击事件
        NSLog(@"%@,%ld",button.currentTitle,(long)didRow);
        //                lab.text = [NSString stringWithFormat:@"%@,下标%ld",button.currentTitle,(long)didRow];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", button.currentTitle];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"商品详情");
    self.view.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
    [self customNavigationItems];
    [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
//    [self addRightBarButtonItemWithTitle:@"收藏" withImage:mImageByName(@"爱心") action:@selector(rightAction:)];
    self.selfTableView.tableHeaderView = self.bannerView;
    self.imageHeightArray = [[NSMutableDictionary alloc]init];
    [self loadGoodDetail];
//    self.popView = [[[NSBundle mainBundle] loadNibNamed:@"AddCartOrBuyView" owner:self options:nil] firstObject];
//    self.popView.axcUI_Size = CGSizeMake(mScreenWidth, mScreenHeight*2/3);
    
    self.cartBtn.axcUI_padding = 2;
    self.cartBtn.axcUI_buttonContentLayoutType = AxcButtonContentLayoutStyleCenterImageTop;
    
    self.phoneBtn.axcUI_padding = 2;
    self.phoneBtn.axcUI_buttonContentLayoutType = AxcButtonContentLayoutStyleCenterImageTop;
}
#pragma mark -
#pragma mark - **************** tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        if (self.goodItem.introduceImages) {
            NSArray * introduceA = [self.goodItem.introduceImages componentsSeparatedByString:@","];
            return introduceA.count + 3;
        }
        return 3;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        GoodInfoCell * itemCell = mGetTableViewCell(@"goodInfoCell");
        if (self.goodItem) {
            [itemCell reloadViewForModel:self.goodItem];
        }
        return itemCell;
    }else if (indexPath.section == 1){
        StoreInfoCell * itemCell = mGetTableViewCell(@"storeInfoCell");
        if (self.goodItem) {
            itemCell.nameLabel.text = self.goodItem.storeName;
            itemCell.distanceLabel.text = [NSString stringWithFormat:@"%@km",self.goodItem.distance];
            [itemCell.logoImageView sd_setImageWithURL:[NSURL URLWithString:self.goodItem.doorImage] placeholderImage:nil];
        }
        itemCell.goStoreDetailBlock = ^{
            StoreDetailViewController * sdvc = mGetStoryboardViewController(@"Main", @"storeDetailViewController");
            sdvc.storeId = self.goodItem.storeId;
            NavigationController_pushVC(sdvc);
        };
        return itemCell;
    }else if (indexPath.section == 3){
        RemGoodsCell * itemCell = mGetTableViewCell(@"remGoodsCell");
        if (self.goodItem) {
            itemCell.dataList = self.goodItem.storeRmdGoods;
        }
        itemCell.returnGoodsDetail = ^(NSString * _Nonnull gid) {
            MDDGoodsDetailViewController * detailVC = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
            detailVC.goodId =gid;
            NavigationController_pushVC(detailVC);
        };
        return itemCell;
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            UITableViewCell * itemCell = mGetTableViewCell(@"headerCell");
            return itemCell;
        }else if (indexPath.row == 1){
            UITableViewCell * goodInfo = mGetTableViewCell(@"goodInfo");
            UILabel * good = mViewByTag(goodInfo.contentView, 100, UILabel);
            good.text = self.goodItem.typeName;
            return goodInfo;
        }else if (indexPath.row == 2){
            UITableViewCell * pinPaiInfo = mGetTableViewCell(@"pinPaiInfo");
            UILabel * pinPai = mViewByTag(pinPaiInfo.contentView, 100, UILabel);
            pinPai.text = self.goodItem.brand;
            return pinPaiInfo;
        }else{
            ImageItemCell * imageInfo = mGetTableViewCell(@"imageItemCell");
            NSArray * introduceA = [self.goodItem.introduceImages componentsSeparatedByString:@","];
            imageInfo.getImageHeight = ^(CGFloat height) {
                if (![[self.imageHeightArray allKeys] containsObject:@(indexPath.row)]) {
                    [self.imageHeightArray setObject:@(height) forKey:@(indexPath.row)];
                    [self.selfTableView beginUpdates];
                    [self.selfTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    [self.selfTableView endUpdates];
                }
            };

            [imageInfo setImgStr:introduceA[indexPath.row -3]];
            return imageInfo;
        }
       
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        return 0.01;
    }
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==  0) {
        return 75;
    }else if (indexPath.section == 1){
        return 88;
    }else if (indexPath.section == 3){
        return (mScreenWidth-30)/3+90;
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
             return 44;
        }else if (indexPath.row == 1){
            return 44;
        }else if (indexPath.row == 2){
            return 44;
        }else{
            
        }
       
    }
    CGFloat height = [[self.imageHeightArray objectForKey:@(indexPath.row)] floatValue];
    if (height>0) {
        return height;
    }
    //给定图片一个默认高度，用于临时占位
    return 200;
}
#pragma mark AxcBannerViewDataSource
// 返回 Banner 需要显示 Item(View) 的个数
- (NSInteger)AxcUI_numberOfItemsInBanner:(AxcUI_BannerView *)banner{
    return 1;
}

// 返回 Banner 在不同的 index 所要显示的 View (可以是完全自定义的v iew, 且无需设置 frame)
- (UIView *)AxcUI_banner:(AxcUI_BannerView *)banner viewForItemAtIndex:(NSInteger)index{
    //    AppADModel * model = self.bannerList[index];
    NSString *imageName = self.goodItem.image;
    // 创建将要显示控件
    UIImageView *imageView = [[UIImageView alloc] init];
    // 加载图片，返回任意View即可，这里使用网络加载图片展示简单轮播
    [imageView sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:[UIImage imageNamed:@"bannerBackImg"]];
    
    //    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    return imageView;
}
// 当self.bannerView.axcUI_showFooter = YES 的时候才会回调这个委托
- (void)AxcUI_bannerFooterDidTrigger:(AxcUI_BannerView *)banner{
    NSLog(@"触发了footer");
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = [UIColor AxcUI_CloudColor];
    vc.title = @"新测试VC";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)AxcUI_banner:(AxcUI_BannerView *)banner didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"点击了第%zi个View",index);
    
}

// 返回 Footer 在不同状态时要显示的文字
- (NSString *)AxcUI_banner:(AxcUI_BannerView *)banner titleForFooterWithState:(AxcBannerFooterState)footerState{
    if (footerState == AxcBannerFooterStateIdle) {
        return @"拖动进入下一页";
    } else if (footerState == AxcBannerFooterStateTrigger) {
        return @"释放进入下一页";
    }
    return nil;
}
#pragma mark 
#pragma mark - **************** 数据请求
-(void)loadGoodDetail
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, self.goodId, @"gid");
    setDickeyobj(parameters, [AppUserBaseModel sharedUserData].latitude, @"latitude");
    setDickeyobj(parameters, [AppUserBaseModel sharedUserData].longitude, @"longitude");
    [PPNetworkHelper POST:app_mall_goodDetail parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            self.goodItem = [[AppBaseGoodItem alloc]init];
            [self.goodItem setValuesForKeysWithDictionary:responseObject[@"data"][@"goodInfo"]];
            self.goodItem.storeRmdGoods = responseObject[@"data"][@"storeRmdGoods"];
            if ([self.goodItem.isCollection isEqualToString:@"0"]) {
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心"] action:@selector(rightAction:)];

            }else{
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心2") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心2"] action:@selector(rightAction:)];

            }
        }else{
            
        }
        [self.bannerView AxcUI_reloadData];
        [self.selfTableView reloadData];
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
#pragma mark - 懒加载区
- (AxcUI_BannerView *)bannerView{
    if (!_bannerView) {
        _bannerView = [[AxcUI_BannerView alloc] initWithFrame:CGRectMake(0, 0, mScreenWidth, mScreenWidth*0.6)];
        _bannerView.axcUI_bannerDataSource = self;
        _bannerView.axcUI_bannerDelegate = self;
        _bannerView.axcUI_shouldLoop = YES;
        _bannerView.axcUI_autoScroll = YES;
        // 设置frame
    }
    return _bannerView;
}
- (NSMutableArray *)bannerList{
    if (!_bannerList) {
                _bannerList = @[@"http://pic.58pic.com/58pic/13/88/95/27p58PICWau_1024.jpg",
                               @"http://images.missyuan.com/attachments/day_080414/20080414_5651a9ad503e6852ae9e6GVhuTdhVFAc.jpg",
                               @"http://pic28.nipic.com/20130424/11588775_115415688157_2.jpg",
                               @"http://ww4.sinaimg.cn/bmiddle/62faf073jw1ds4rt49wbqg.gif"];
    }
    return _bannerList;
}


@end
